<template>
	<view v-if="dataReady" class="cc">
		<view class="cart" :style="cartHeight">
		<!-- 自定义导航栏 -->
			<view>
				<van-nav-bar right-text="管理">
					<view slot="title">
						<text class="cart-title">购物车</text>
					</view>
					<view slot="left">
						<image class="cart-icon" src="/static/btn.png" @click="onCLickLeft"/>
					</view>
				</van-nav-bar>
			</view>
		
		    <!-- 正常的购物车数据 -->
			<view class="cart-settle-item">
				<settle-item
					v-if="data_in_cart.length"
				    v-for="(data, index) in data_in_cart"
					:key="index"
					:idx-in-cart="index"
				    :shop-data="data"/>
			</view>
		
		    <!-- 已失效商品 -->
			<inactive-goods 
				v-if="data_inactive.length"
				:product-data="data_inactive"/>
		
		</view>
		<!-- 底部工具栏 -->
		<settlement-bar/>
	</view>
</template>

<script setup>
	// 常规导入
	import { ref, computed, watch, onMounted, nextTick } from "vue";
	
	// 自定义组件
	import SettleItem from "./secondLevel/settleItem.vue";
	import SettlementBar from "./secondLevel/settlementBar.vue";
	import InactiveGoods from "./secondLevel/inactiveGoods.vue";
	
	// 后端请求相关
	import decMallApi from "/api/dec/decIndex/decMallApi";

	// 全局状态isChosen, totalPrice, count相关
	import { storeToRefs } from "pinia"
	import { useTotalPriceStore } from "./stores/totalPrice";
	import { useIsChosenStore } from "./stores/isChosen";
	import { useCountStore } from "./stores/count";
	
	const { isChosen, computePrice } = storeToRefs(useIsChosenStore());
	const { initIsChosen, initIsInactiveProductChosen, updateIsInactiveProductChosen } = useIsChosenStore();
	
	const { totalPrice } = storeToRefs(useTotalPriceStore());
	const { updateTotalPrice } = useTotalPriceStore();
	
	const { count, countChange } = storeToRefs(useCountStore());
	const { initCount } = useCountStore();
	
	// 全局状态globalData
	import { useGlobalDataStore } from "@/globalData.js";
	const { globalData } = storeToRefs(useGlobalDataStore());
	
	const dataReady = ref(false);
	
	// 计算总价
	watch([computePrice, countChange], ()=>{
		let tprice = 0;
		isChosen.value.forEach((shop, idx_of_shop)=>{
			shop.product.forEach((item, idx_of_product)=>{
				const price = data_in_cart.value[idx_of_shop].product_data[idx_of_product].product_price;
				const num = count.value[idx_of_shop].product[idx_of_product];
				console.log("item: ", item , "price:" , price, "num: ", num);
				tprice += item * price * num;
			})
		})
		console.log("totalPrice in cartDetails: ", tprice);
		updateTotalPrice(tprice);
	})

	const onCLickLeft = () => {
		console.log("click left")
		uni.navigateBack({
		  delta: 1 // 返回的层级，默认为1，即返回到上一级页面
	});
}

	const tmpURL = "https://inews.gtimg.com/om_bt/OkEPpEM1AZfKFIi1Xq5YapKDWpVWWex8WQ-HJ-QG3VPO0AA/641";
	const baseImgUrl = 'https://upload.gfinter.net/';
	// 购物车正常加载的数据
	const data_in_cart = ref([
	//   {
	// 	supplier_name: "A服装店",
	// 	product_data: [
	// 	  {product_title: "商品1", product_attr_str: "", product_price: 400.30, num: 1, product_ico: tmpURL},
	// 	  {product_title: "商品2", product_attr_str: "", product_price: 500.01, num: 1, product_ico: tmpURL},
	// 	]
	//   },
	//   {
	// 	supplier_name: "B服装店",
	// 	product_data: [
	// 	  {product_title: "商品3", product_attr_str: "", product_price: 400.21, num: 1, product_ico: tmpURL},
	// 	  {product_title: "商品4", product_attr_str: "", product_price: 500, num: 1, product_ico: tmpURL},
	// 	  {product_title: "商品s", product_attr_str: "", product_price: 800.29, num: 1, product_ico: tmpURL}
	// 	]
	//   },
	]);
	// 失效的数据
	const data_inactive = ref([
		{supplier_name: "A服装店", state: "已下架", product_title: "商品5", product_attr_str: "规格", product_price: '400.10', num: 1, product_ico: tmpURL},
		{supplier_name: "A服装店", state: "已售罄", product_title: "商品6", product_attr_str: "规格", product_price: '500.10', num: 1, product_ico: tmpURL},
	])
	
	// 处理请求得到的数据 res
	function get_data_in_cart(res){
		const initValue = [];
		const newRes = res.reduce((acc, cur) => {
		    // 查找是否已经存在了该 supplier_id 的分类
		    const existingGroup = acc.find(group => group.supplier_id === cur.supplier_id);
			// 处理cur.product_ico
			cur.product_ico = baseImgUrl + cur.product_ico;
			
		    if (existingGroup) {
		        // 如果找到了，则直接将相关值添加到已有的数组中
		        existingGroup.product_data.push(cur);
		    } else {
		        // 如果没有找到，则新建一个对象
		        acc.push({ 
					supplier_id: cur.supplier_id, 
					supplier_name: cur.supplier_name, 
					product_data: [cur],
				});
		    }
		
		    return acc;
		}, initValue);
		console.log("前端处理得到的购物车数据后：", newRes);
		return newRes;
	}

	// 获得购物车商品详情
	async function Cart_detail(){
		const params = {
			visit_gfid: globalData.value.VISIT_DATA.visit_gfid, 
			show_down: 1
		}
		try{
			const res = await decMallApi.Get_shopping_car_products_API(params);
			console.log("Cart_detail 获取成功", res)
			data_in_cart.value = get_data_in_cart(res.datas);
			data_inactive.value = res.disabled_datas;
		
			// 初始化全局状态isChosen
			let newData = data_in_cart.value.map((item, idx) => {
				return {
					shop: false,
					product: new Array(item.product_data.length).fill(false)
				}
			})
			initIsChosen(newData);
			console.log("initIsChosen: ", newData);
			// 初始化全局状态isInactiveChosen
			newData = new Array(data_inactive.value.length).fill(false);
			initIsInactiveProductChosen(newData);
			console.log("initIsInactiveChosen: ", newData);
			// 初始化全局状态count
			newData = data_in_cart.value.map((item, idx) => {
				return {
					product: new Array(item.product_data.length).fill(1)
				}
			})
			initCount(newData);
			console.log("initCount: ", newData);
			
		}catch(err){
			console.log('Cart_detail 获取失败',err);
		}
	}

	async function init(){
		await Cart_detail();
	}
	
	onMounted(async ()=>{
		dataReady.value = false;
		await init();
		dataReady.value = true;
	})
	
	// 样式控制
	import { getCurrentInstance } from 'vue';
	const instance = getCurrentInstance();
	const cartHeight = ref('');
	watch(dataReady, async ()=>{
		let distanceToBottom ;
		await nextTick(() => {
			const query = uni.createSelectorQuery().in(instance.proxy);
			query.select(".cart")
			  .boundingClientRect((data) => {
				  if(data){ // 确保data不为null
					  console.log(data)
					  const systemInfo = uni.getSystemInfoSync(); // 使用uni.getSystemInfoSync获取视口高度
					  const windowHeight = systemInfo.windowHeight; // 视口高度
					  distanceToBottom = windowHeight - (data.top + data.height);
					  cartHeight.value = distanceToBottom > 0 ? { 'height': '83%' } : null;
					  console.log("节点到底部的距离为 ", distanceToBottom);
				  } else {
					  console.error('未找到指定的元素');
				  }
			  })
			  .exec();
		});
	})
</script>

<style lang="scss">
	.cart{
		background-color: rgb(247, 247, 249);
		padding-bottom: 150rpx; // 防止被底部的view遮挡
		&-title{
			font-weight: bold;
			margin-bottom: 10rpx;
		}
		&-icon{
			height: 40rpx;
			width: 40rpx;
			margin-top: 10rpx;
			cursor: pointer;
		}
	}
	.cc{
		height: 100%;
	}
</style>